// ============================== 导入依赖 ============================== //

import CORE from '@login/CORE'
import TRANS from '@demo/CORE/UTIL/init/TRANS'

import Client from '@api/base/api/SysDictRegionApi'

import TreeClass from '@api/base/model/SysDictRegionQueryDto'

const CLIENT = CORE.grpcCLIENT(Client)

// ============================== 导出远程接口 ============================== //

export default {
  // —————————————————————————————— 结构树 —————————————————————————————— //

  async getDistrict(name = '行政区') {
    if (sessionStorage.DISTRICT) return JSON.parse(sessionStorage.DISTRICT)

    const DTO = CORE.grpcDTO(TreeClass)
    const resp = await CORE.grpc(TRANS.transTip(name), CLIENT, 'sysDictRegionQuery', DTO)

    const DISTRICT = trans(resp)
    sessionStorage.DISTRICT = JSON.stringify(DISTRICT)
    return DISTRICT
  },
}

// —————————————————————————————— 转换省市区 —————————————————————————————— //

const trans = ({ provinceList, cityList, countyList }) => {
  // 城市
  const cityMap = {}
  const citys = Object.keys(cityList).map((id) => {
    cityMap[id] = []
    return { children: cityMap[id], id: +id, name: cityList[id], describe: `${id}` }
  })

  // 区县
  Object.keys(countyList).forEach((id) => {
    const cityChildren = cityMap[id - id % 100] || []
    cityChildren.push({ children: [], id: +id, name: countyList[id], describe: `${id}` })
  })

  // 省份
  return Object.keys(provinceList).map((id) => {
    const children = citys.filter((city) => city.id - city.id % 10000 === +id)
    return { children, id: +id, name: provinceList[id], describe: `${id}` }
  })
}
